package com.fstec.ks.master.netty.receiver;

import java.io.File;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.fstec.ks.master.MasterEngine;
import com.fstec.ks.master.netty.ResponseMessageType;
import com.fstec.ks.master.netty.receiver.bean.RoundBakBean;
import com.fstec.ks.master.vo.ExamServerVO;
import com.sinotn.SinotnLogger;
import com.sinotn.gson.GsonFacade;
import com.sinotn.ks.definition.Computer;
import com.sinotn.ks.definition.Message;
import com.sinotn.ks.definition.MessageFile;
import com.sinotn.ks.definition.MessageReceiver;
import com.sinotn.ks.netty.message.SimpleMessage;
import com.sinotn.util.FileUtil;

/**
 * 场次数据数据备份
 * @Title RoundBakReceiver.java
 * @Package com.fstec.ks.master.netty.receiver
 * @Description 
 * Copyright: Copyright (c) 2023
 * Company:广东峰上科技有限公司
 * 
 * @author <a href="mailto:xieqj@fstec.com">谢启进</a>
 * @date 2023年10月13日 下午2:43:44
 * @version V1.0
 */
public class RoundBakReceiver implements MessageReceiver {
	@Autowired
	private MasterEngine masterEngine;
	private int type=203;
	@Override
	public int getType() {
		return this.type;
	}

	public void setType(int type) {
		this.type = type;
	}

	@Override
	public void process(Computer computer, Message msg) {
		MessageFile[] mfs=msg.getFiles();
		try{
			RoundBakBean roundBakBean=GsonFacade.fromJson(msg.getText(), RoundBakBean.class);
			File file=mfs[0].getFile();
			String regKey=computer.getRegKey();
			String serverSign=FileUtil.getCrc32Sign(file);
			if(roundBakBean.getSign().equals(serverSign)){
				this.masterEngine.backupRoundData(regKey, new Date(roundBakBean.getUploadTime()), roundBakBean.getRounds(), mfs[0].getFile());
			}else{
				ExamServerVO examServer=this.masterEngine.getExamServer(regKey);
				SinotnLogger.DEBUG.error("考试服务{}场次数据备份文件签名不通过{}->{}", examServer.getExamServerName(), roundBakBean.getSign(), serverSign);
			}
			SimpleMessage sm=new SimpleMessage(ResponseMessageType.SUCCESS, msg.getToken());
			computer.sendMessage(sm);
		}finally{
			if(mfs!=null && mfs.length>0){
				for(MessageFile mf:mfs){
					mf.delete();
				}
			}
		}
	}
}
